<?php

namespace app\controller;

use think\facade\Db;

class Search
{
    public function searchYard()
    {
        $query = input('get.query', '');
        $page = input('get.page', 1);
        $limit = input('get.limit', 10);
        $offset = ($page - 1) * $limit;

        $yardList = Db::table('cdydpt_info')
            ->where('campusname', 'LIKE', "%$query%")
            ->whereOr('yard_name', 'LIKE', "%$query%")
            ->whereOr('yard_type', 'LIKE', "%$query%")
            ->limit($offset, $limit)
            ->select();

        if (!$yardList) {
            return json(['error' => 'No yard list found'], 404);
        }

        foreach ($yardList as &$yard) {
            // 检查 yard_image 是否为空
            if (!empty($yard['yard_image'])) {
                // 将 yard_image 转换为 Base64 编码
                $yard['yard_image'] = 'data:image/jpeg;base64,' . base64_encode($yard['yard_image']);
            } else {
                $yard['yard_image'] = ''; // 如果图片为空，设置为空字符串
            }
        }

        // 将数据转换为 UTF-8 编码
        array_walk_recursive($yardList, function(&$item, $key) {
            if (!mb_detect_encoding($item, 'utf-8', true)) {
                $item = utf8_encode($item);
            }
        });

        return json($yardList);
    }
}
